/*
 * MainFrame.java
 *
 * Created on 1. Februar 2007, 20:26
 *
 * Copyright (c) 2007 Daniel Gronau
 *
 * This file is part of KanjiTori.
 *
 * KanjiTori is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * KanjiTori is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

package kanjitori;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ResourceBundle;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import kanjitori.abstraction.AbstractFactoryXmlLoader;
import kanjitori.lesson.ExtensionLessonLoader;
import kanjitori.lesson.Lesson;
import kanjitori.lesson.Section;
import kanjitori.map.ExtensionMapLoader;
import kanjitori.map.Map;
import kanjitori.preferences.KeyMap;

/**
 *
 * @author Pirx
 */
public class MainFrame {
    
    public static Image STARTUP_IMAGE = new ImageIcon("./data/kanjitori1.png").getImage();
    
    private ResourceBundle bundle = ResourceBundle.getBundle("kanjitori/resources/String");
    
    private Lesson lesson = null;
    private Map map = null;
    private JFrame frame;
    
    private JLabel lessonLabel;
    private JLabel mapLabel;
    private SpinnerNumberModel maxEntriesModel;
    private JComboBox freqBox;
    private JComboBox resBox;
    private JComboBox colBox;
    private JCheckBox fullCheckBox;
    private JCheckBox invertMouseCheckBox;
    private JComboBox[][] keyComboBoxes;
    
    /** Creates a new instance of MainFrame */
    public MainFrame() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                initFrame();
            }
        });
    }
    
    public void initFrame() {
        frame = new JFrame("KanjiTori");
        frame.setSize(600,400);
        JTabbedPane tabs = new JTabbedPane();
        tabs.add(bundle.getString("Lesson"), getLessonTab());
        tabs.add(bundle.getString("Map"), getMapTab());
        tabs.add(bundle.getString("KeyMap"), getKeyTab());
        tabs.add(bundle.getString("VideoSettings"), getVideoTab());
        frame.getContentPane().add(tabs);
        frame.getContentPane().add(getSouth(), BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    
    public JPanel getLessonTab() {
        JPanel panel = new JPanel(new BorderLayout());
        Box north = Box.createHorizontalBox();
        JButton loadLessonButton = new JButton(bundle.getString("loadLesson"));
        final JPanel center = new JPanel(new BorderLayout());
        panel.add(center);
        loadLessonButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                loadLesson(center);
            }
        });
        north.add(loadLessonButton);
        north.add(Box.createHorizontalStrut(10));
        north.add(lessonLabel = new JLabel(bundle.getString("noLessonLoaded")));
        panel.add(north, BorderLayout.NORTH);
        Box south = Box.createHorizontalBox();
        south.add(new JLabel(bundle.getString("MaxEntries")));
        south.add(Box.createHorizontalStrut(10));
        maxEntriesModel = new SpinnerNumberModel(1000,10,10000,1);
        south.add(new JSpinner(maxEntriesModel));
        south.add(Box.createHorizontalGlue());
        panel.add(south, BorderLayout.SOUTH);
        return panel;
    }
    
    private void loadLesson(JPanel panel) {
        FileFilter ff = new FileFilter() {
            public boolean accept(File f) {
                return f.getName().endsWith(".lsn");
            }
            public String getDescription() {
                return bundle.getString("KanjiToriLessons") + " (*.lsn)";
            }
        };
        JFileChooser fc = new JFileChooser("./lesson");
        fc.setFileFilter(ff);
        int retVal = fc.showOpenDialog(frame);
        if (retVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            lesson = ExtensionLessonLoader.getInstance().get(file.getAbsolutePath());
            lessonLabel.setText(file.getAbsolutePath());
            Box center = Box.createVerticalBox();
            for (int i = 0; i < lesson.size(); i++ ) {
                final Section section = lesson.getSection(i);
                JCheckBox chBox = new JCheckBox(section.getName(),true);
                chBox.addItemListener(new ItemListener(){
                    public void itemStateChanged(ItemEvent e) {
                        section.setIncluded(e.getStateChange() == ItemEvent.SELECTED);
                    }
                });
                center.add(chBox);
            }
            panel.removeAll();
            panel.add(new JScrollPane(center));
        }
    }
    
    public JPanel getMapTab() {
        JPanel panel = new JPanel(new BorderLayout());
        Box north = Box.createHorizontalBox();
        JButton loadMapButton = new JButton(bundle.getString("loadMap"));
        loadMapButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                loadMap();
            }
        });
        north.add(loadMapButton);
        north.add(Box.createHorizontalStrut(10));
        north.add(mapLabel = new JLabel(bundle.getString("noMapLoaded")));
        panel.add(north, BorderLayout.NORTH);
        return panel;
    }
    
    public void loadMap() {
        FileFilter ff = new FileFilter() {
            public boolean accept(File f) {
                return f.getName().endsWith(".bsh") || f.getName().endsWith(".map");
            }
            public String getDescription() {
                return bundle.getString("KanjiToriMaps") + " (*.map, *.bsh)";
            }
        };
        JFileChooser fc = new JFileChooser("./map");
        fc.setFileFilter(ff);
        int retVal = fc.showOpenDialog(frame);
        if (retVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            map = ExtensionMapLoader.getInstance().get(file.getAbsolutePath());
            mapLabel.setText(file.getAbsolutePath());
        }
    }
    
    public JPanel getKeyTab() {
        JPanel panel = new JPanel(new BorderLayout());
        JPanel inner = new JPanel(new GridLayout(KeyMap.ACTIONS.length + 1, 3, 10,10));
        panel.add(new JScrollPane(inner), BorderLayout.CENTER);
        KeyMap keyMap = null; //KeyMap.getInstance();
        keyComboBoxes = new JComboBox[KeyMap.ACTIONS.length][2];
        String[] values = new String[KeyMap.KEYS.length+1];
        values[0] = "";
        for (int i = 0; i < KeyMap.KEYS.length; i++) {
            values[i+1] = KeyMap.KEYS[i].length() == 1 
                    ? KeyMap.KEYS[i]
                    : bundle.getString("Key_" + KeyMap.KEYS[i]);
        }
        for (int i = 0; i < KeyMap.ACTIONS.length; i++) {
           inner.add(new JLabel(bundle.getString("Action_" + KeyMap.ACTIONS[i]),JLabel.RIGHT));
           for (int n = 0; n < 2; n++) {
              inner.add(keyComboBoxes[i][n] = new JComboBox(values)); 
              keyComboBoxes[i][n].setSelectedIndex(0);
           }
        }
        for (int k = 0; k < KeyMap.KEY_INPUT.length; k++) {
            String action = keyMap.getAction(KeyMap.KEY_INPUT[k]);
            if (action != null) {
                int actionIndex = KeyMap.getActionIndex(action);
                JComboBox combo = keyComboBoxes[actionIndex][0];
                if (combo.getSelectedIndex() <= 0) {
                    combo.setSelectedIndex(k + 1);
                } else {
                    keyComboBoxes[actionIndex][1].setSelectedIndex(k + 1);
                }
            }
        }
        
        inner.add(new JLabel(bundle.getString("InvertMouse"),JLabel.RIGHT));
        invertMouseCheckBox = new JCheckBox("", keyMap.isMouseInverted());
        inner.add(invertMouseCheckBox);
        inner.add(new JLabel());
        return panel;
    }
    
    public JPanel getVideoTab() {
        //VideoSettings vs = VideoSettings.getInstance();
        
        JPanel panel = new JPanel(new BorderLayout());
        /*JPanel inner = new JPanel(new GridLayout(4, 2, 10,10));
        panel.add(inner, BorderLayout.NORTH);
        inner.add(new JLabel(bundle.getString("Frequency"),JLabel.RIGHT));
        freqBox = new JComboBox(VideoSettings.FREQUENCIES);
        freqBox.setSelectedIndex(vs.getFreqIndex());
        inner.add(freqBox);
        inner.add(new JLabel(bundle.getString("Resolution"),JLabel.RIGHT));
        resBox = new JComboBox(VideoSettings.RESOLUTIONS);
        resBox.setSelectedIndex(vs.getResIndex());
        inner.add(resBox);
        inner.add(new JLabel(bundle.getString("ColorDepth"),JLabel.RIGHT));
        colBox = new JComboBox(VideoSettings.COLORS);
        colBox.setSelectedIndex(vs.getColorIndex());
        inner.add(colBox);
        inner.add(new JLabel(bundle.getString("Fullscreen"),JLabel.RIGHT));
        fullCheckBox = new JCheckBox("", vs.isFullscreen());
        inner.add(fullCheckBox);*/
        return panel;
    }    
    
    public static void main(String... args) {
        AbstractFactoryXmlLoader.init("factories.xml");
        new MainFrame();
    }
    
    private JPanel getSouth() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton learnButton = new JButton(bundle.getString("Learn"));
        learnButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event) {
                startGame();
            }
        });
        panel.add(learnButton);
        return panel;
    }
    
    private void startGame() {
        if (lesson == null) {
            JOptionPane.showMessageDialog(frame, bundle.getString("noLessonLoaded"));
            return;
        }
        if (map == null) {
            JOptionPane.showMessageDialog(frame, bundle.getString("noMapLoaded"));
            return;
        }
        lesson.setMaxEntries(maxEntriesModel.getNumber().intValue());
        /*VideoSettings vs = VideoSettings.getInstance();
        vs.setFrequency(Integer.parseInt((String) freqBox.getSelectedItem()));
        vs.setDepth(Integer.parseInt((String) colBox.getSelectedItem()));
        String[] res = ((String)resBox.getSelectedItem()).split("x"); 
        vs.setWidth(Integer.parseInt(res[0]));
        vs.setHeight(Integer.parseInt(res[1]));
        vs.setFullscreen(fullCheckBox.isSelected());*/
        KeyMap keyMap = null; //KeyMap.getInstance();
        keyMap.setMouseInverted(invertMouseCheckBox.isSelected());
        for (int i = 0; i < KeyMap.ACTIONS.length; i++) {
            for (int j = 0; j < 2; j++) {
                int keyIndex = keyComboBoxes[i][j].getSelectedIndex();
                if (keyIndex > 0) {
                    keyMap.bind(KeyMap.KEYS[keyIndex - 1], KeyMap.ACTIONS[i]);
                }
            }
        }
        Map tempMap = map;
        map = null;
        //keyMap.save();
        //VideoSettings.getInstance().save();
        try {
            Main.startGame(lesson, tempMap);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(frame, ex.getMessage());
        }
    }
}
